package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;



import com.google.android.gms.maps.model.LatLng;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import app.Disthanitian.thaistyle.EmerMez.DistanceDetection.FindDistance;

public class ChangeStatus extends Activity {

	private String msgRed = "";	
	private String msgYelllow = "";
	private int timeToUpdateLocation;	
	private String pinCode;
	MemberUserLog log = new MemberUserLog();
	MainActivity main;
	MemberUser memUser;
	LatLng currentPosition;
	AlertDialog dia,alertPinCode;
	CountDownTimer time,timeForPinCode,timeCheckPosition,timeForUpdateLog;
	boolean isCheckTitle;	
	Document doc;	
	
	int count=0;
	String urls;
	double distance1=0,distance2,result;
	boolean check = true;
	boolean checking;
	int countForInputPin;
	long timess;
	String status = "green";
	boolean isRisk = false;
	AddUserLog userLog = new AddUserLog();
	
	SessionManager session;
	
	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setContentView(R.layout.changestatus);
		
		 // Session class instance
		session = new SessionManager(getApplicationContext());
		
		 HashMap<String, String> user = session.getUserDetails();
	        
	        // name
	        String name = user.get(SessionManager.KEY_NAME);
	        
	        // email
	        String email = user.get(SessionManager.KEY_EMAIL);
	        
	        String id = user.get(SessionManager.KEY_ID);
	        
	        String time2 = user.get(SessionManager.KEY_TIME);
	        
	        int TIME;

			   if(time2!=null){
				    TIME = Integer.parseInt(time2);
				    MemberUser.setTimeLocateUpdate(TIME);
		        }	
			   
	        String MSGY = user.get(SessionManager.KEY_MSGY);
	       
	        String MSGR = user.get(SessionManager.KEY_MSGR);
		
		   Toast.makeText(getApplicationContext(), "User Login Status: " +session.isLoggedIn() +"\n" , Toast.LENGTH_LONG).show();
		   
		   MemberUser.setId(id);
	       MemberUser.setFirstname(name);
	       MemberUser.setEmail(email);
	       //MemberUser.setTimeLocateUpdate(Integer.parseInt(time2));
	       MemberUser.setMsgYellow(MSGY);
	       MemberUser.setMsgRed(MSGR);
		
	  	//String Status = memUser.getStatusLogin();
		//Toast.makeText(ChangeStatus.this, Status,Toast.LENGTH_LONG).show();
		
		final Handler handler = new Handler();
		
		//changeTimeLabel();
		
		// Set Preference Variable
		/*msgRed = SettingView.getMessageRed(ChangeStatus.this);
		msgYelllow = SettingView.getMessageYellow(ChangeStatus.this);
		pinCode = SettingView.getPinCode(ChangeStatus.this);		
		main= new MainActivity(); */
		
		//myLocation();
		
		
		/*checkInRiskZone();
		timeForUpdateLog = new CountDownTimer(10000,10) {
			
			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				setMemberUserValue(myLocation());
				updateLog(memUser);
				Toast.makeText(ChangeStatus.this, "Has Updated", 3).show();
				timeForUpdateLog.start();
			}
		}.start(); */
		//main.isInRiskZone(main.getDirectionPointArray(), ChangeStatus.this);
		/*String urls = "http://maps.googleapis.com/maps/api/directions/xml?origin="
				+ 13.6430202785360075 + "," + 100.59328123927116
				+ "&destination=" + 13.642850528321748 + ","
				+ 100.59407114982605
				+ "&sensor=false&units=metric&mode=walking";
		
		FindDistance f = new FindDistance();
		f.execute(urls);*/
		
		//intervalCheckDistance();
		
		
		
			setButton();

	}
	
	//Click onBackPressed Button Device

	public void onBackPressed() {
	    new AlertDialog.Builder(this)
	        .setTitle("Really Exit?")
	        .setMessage("Are you sure you want to exit?")
	        .setNegativeButton("No", null)
	        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					//ChangeStatus.super.onBackPressed();
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_HOME);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
			}).show();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		// getMenuInflater().inflate(R.menu.main, menu);
		actionBar();
		return true;
	}

	public void actionBar() {
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		actionBar.setDisplayShowTitleEnabled(false);
		SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this,
				R.array.action_list,
				android.R.layout.simple_spinner_dropdown_item);
		ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {

			@Override
			public boolean onNavigationItemSelected(int itemPosition,
					long itemId) {
				lanuchItemSelected(itemPosition);

				return true;

			}
		};
		actionBar.setListNavigationCallbacks(mSpinnerAdapter,
				navigationListener);
	}

	private void lanuchItemSelected(int item) {
		Intent i;

		switch (item) {
		case 1:
			i = new Intent(this, MainActivity.class);
			// Toast.makeText(ChangeStatus.this,item,
			// Toast.LENGTH_SHORT).show();
			startActivity(i);

			break;

		case 2:
			i = new Intent(this, SettingActivity.class);
			startActivity(i);
			break;
		case 3:
			i = new Intent(this, About.class);
			startActivity(i);
			break;

		case 4:
			session.logoutUser();
			i = new Intent(this, LoginActivity.class);
			i.putExtra("StatusLogout","logout");
			startActivity(i);
			Toast.makeText(ChangeStatus.this, "Logout !!", Toast.LENGTH_LONG).show();
			break;

		}
	}

	public void setButton() {
		Button btnGreen = (Button) findViewById(R.id.green_btn);
		btnGreen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				callManucalGreen();
			}
		});
		Button btnYellow = (Button) findViewById(R.id.yellow_btn);
		btnYellow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				callManualYellow();
			}
		});
		Button btnRed = (Button) findViewById(R.id.red_btn);
		btnRed.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				callManualRed();
			}
		});
	}

	// Call Functions name	
	@SuppressWarnings("deprecation")
	public void callManualYellow() {
		if(timeCheckPosition!=null)
			timeCheckPosition.cancel();
		
		status = "yellow";
		dia = new AlertDialog.Builder(ChangeStatus.this).create();
		dia.setTitle("Alert option");
		dia.setMessage("Do you want to change your status to risk?" + "00:");
		dia.setButton("Yes",
		new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				time.cancel();
				View changeStatusBg = findViewById(R.id.changeStatusBg);
				changeStatusBg.setBackgroundColor(R.color.yellow2);
				Toast.makeText(ChangeStatus.this,"Your position is being track",3).show();
				intervalCheckDistance();
				
				
				//changeTimeLabel();
				
			}
		});
		dia.setButton2("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				time.cancel();
				
				timeCheckPosition.start();
				// do nothing
			}
		});
		dia.show();

		time = new CountDownTimer(10000, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {

				dia.setMessage("Do you want to change your status to risk? 	\nTime: "
						+ "00:0" + (millisUntilFinished / 1000));

			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				View changeStatusBg = findViewById(R.id.changeStatusBg);
				changeStatusBg.setBackgroundColor(R.color.yellow2);
				Toast.makeText(ChangeStatus.this,
						"Your position is being track", 3).show();
				dia.cancel();
				time.cancel();
			}

		}.start();
		
	}

	public void callManucalGreen(){
		if(status.equals("red") || status.equals("yellow")){
			showPinCode();
			View changeStatusBg = findViewById(R.id.changeStatusBg);
			changeStatusBg.setBackgroundColor(R.color.Green);
		}
	}
	
	public void callManualRed() {
		status = "red";
		View changeStatusBg = findViewById(R.id.changeStatusBg);
		changeStatusBg.setBackgroundColor(R.color.redbtn);

		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendTextMessage("Phone Number", null, "Message", null, null);

		new AlertDialog.Builder(this)
				.setTitle("Status alert")
				/*.setMessage(
						"You are in emergency.\nThe SMS is sent to your contacts.")*/
				.setMessage(msgRed)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						View changeStatusBg = findViewById(R.id.changeStatusBg);
						changeStatusBg.setBackgroundColor(R.color.yellow2);
						Toast.makeText(ChangeStatus.this,
								"Your status is in emergency (RED).", 3).show();
						Toast.makeText(ChangeStatus.this, "Enter PIN to exit",
								3).show();
					}
				}).show();

	}

	

	public void changeTimeLabel(long time){
		//second
		timess = time;
		Handler handler = new Handler();
		
    	
		        Runnable r = new Runnable() {
		            public void run() {	    
		            	TextView textView = (TextView) findViewById(R.id.timerLabel);
		            	int times = 60;
		                times--;
		                textView.setText("Countdown time: "+timess/1000+" seconds" );
		            }
		            
		        };
		        handler.postDelayed(r, 1000);
	}
	
	public LatLng myLocation(){		
		Criteria criteria = new Criteria();
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		String provider = locationManager.getBestProvider(criteria,
				false);
		Location location = locationManager
				.getLastKnownLocation(provider);
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		LatLng currentPosition = new LatLng(lat, lng);
				
		return currentPosition;
	}
	
	public void intervalCheckDistance(){
		
		time = new CountDownTimer(10000, 5000) {
			@Override
			public void onTick(long millisUntilFinished) {
				
				
				
				
				LatLng x[] = new LatLng[5];
				LatLng x1 = new LatLng(13.6430202785360075,100.59328123927116);
				LatLng x2 = new LatLng(13.642850528321748,100.59407114982605);
				
				x[0] = new LatLng(13.6430202785360075,100.59328123927116);
				x[1] = new LatLng(13.683809569574711,100.53873382508755);
				x[2] = new LatLng(13.642850528321748,100.59407114982605);
				x[3] = new LatLng(13.683809569574711,100.53873382508755);
				x[4] = new LatLng(13.6430202785360075,100.59328123927116);					
				createDocument(x[0],x[1]);
				switch(count){
				case 0:createDocument(x[0],x[1]);break;
				case 1:createDocument(x[1],x[2]);break;
							
				
				}
			}
			@SuppressWarnings("deprecation")
			@Override
			public void onFinish() {				
				count++;
				if(isDistanceNormal()){
					Toast.makeText(ChangeStatus.this, "Your speed is normal.", 3).show();									
					doc = null;
				}else{
					time.cancel();					
					Toast.makeText(ChangeStatus.this, "Your speed is abnormal.", 3).show();	
					countForInputPin = 0;
					timeForPinCode = new CountDownTimer(10000,1000) {
						
						@Override
						public void onTick(long millisUntilFinished) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void onFinish() {
							// TODO Auto-generated method stub
							alertPinCode.cancel();
							callManualRed();
							time.cancel();
							timeForPinCode.cancel();
						}
					}.start();
					showPinCode();
					
				}			
				
				time.start();	
			}

		}.start();

	}
		
	public class FindDistance extends AsyncTask<String, Void, Document> {
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            
        }

        @Override
        protected Document doInBackground(String... params) {
            String url = params[0];
            
            DistanceDetection distance = new DistanceDetection();
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                InputStream in = response.getEntity().getContent();
                DocumentBuilder builder = 
                DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = builder.parse(in);                         
                Log.d("FirstDistance",""+distance.getDistanceText(doc));
               

            } catch (Exception e) {
                e.printStackTrace();
            }

            return doc;
        }

        @Override
        protected void onPostExecute(Document result) {

            super.onPostExecute(result);
            


        }

    }
		
	boolean isDistanceNormal(){	
		
		DistanceDetection distance = new DistanceDetection();
		if(doc!=null){
			Log.d("TestDistance",""+distance.getDistanceValue(doc));
			Toast.makeText(ChangeStatus.this, "Disvalue: "+distance.getDistanceValue(doc)+" metres", 3).show();
			distance2 = distance1;
			distance1 = distance.getDistanceValue(doc);
			result = distance1-distance2;
			
			if(result==0 || (result<=(distance1*80)/100 || result>=(distance1*120/100))){
				check = false;
				result = 0;
				
			}
			
		}else{
			check = true;			
			result = 0;
		}
		
		doc= null;
		return check;
	}
	
	public void createDocument(LatLng currentPosition,LatLng nexposition){
		LatLng x1,x2;
		x1 = currentPosition;
		x2 = nexposition;
		urls = "http://maps.googleapis.com/maps/api/directions/xml?origin="
				+ x1.latitude + "," + x2.longitude
				+ "&destination=" + x2.latitude + ","
				+ x2.longitude
				+ "&sensor=false&units=metric&mode=walking";		
		FindDistance f = new FindDistance();
		f.execute(urls);
	}
	
	public boolean checkPinCode(String code){
		if(code.equals(pinCode)){
			return true;
		}else{
			return false;
		}
	}
	
	@SuppressWarnings("deprecation")
	public void showPinCode(){
		if(countForInputPin==3){
			callManualRed();
			time.cancel();
			timeForPinCode.cancel();
			countForInputPin = 0;
		}else{
		alertPinCode = new AlertDialog.Builder(ChangeStatus.this).create();
		alertPinCode.setTitle("Pin Code");
		alertPinCode.setMessage("Type your PIN Code.");					
		final EditText input = new EditText(ChangeStatus.this);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		alertPinCode.setView(input);
		alertPinCode.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				
				Editable value = input.getText();
				String value1 = value.toString();			
				
					if(checkPinCode(value1)){
						if(timeForPinCode!=null)
						timeForPinCode.cancel();
						//callManucalGreen();
						Toast.makeText(ChangeStatus.this, "Correct PIN Code", 3).show();
						time.cancel();
						checking = true;	
						countForInputPin = 0;
					}else{
						checking = false;
						countForInputPin++;
						
						//showPinCode();
						callManucalGreen();
						Toast.makeText(ChangeStatus.this, "Incorrect PIN Code", 3).show();
						time.cancel();
					}			
					
				
				
				
			
			}
		});
		alertPinCode.setButton2("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						//callManualRed();
						time.cancel();
						if(timeForPinCode != null)
							timeForPinCode.cancel();
						
					}
				});		
		alertPinCode.show();
		
	}
	}

	public void checkInRiskZone(){
		//currentPosition = x;
		main = new MainActivity();				
		timeCheckPosition = new CountDownTimer(10000,10) {
			
			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				LatLng x[] = new LatLng[5];
				LatLng x1 = new LatLng(13.6430202785360075,100.59328123927116);
				LatLng x2 = new LatLng(13.642850528321748,100.59407114982605);
				
				x[0] = new LatLng(13.686984727473613,100.5353207171161);
				x[1] = new LatLng(13.687031961980917,100.53541157394648);
				x[2] = new LatLng(13.687011113647824,100.53548097610474);
				x[3] = new LatLng(13.683809569574711,100.53873382508755);
				x[4] = new LatLng(13.6430202785360075,100.59328123927116);					
				
				switch(count){
				case 0:currentPosition=x[0];break;
				case 1:currentPosition=x[1];break;
				case 2:currentPosition=x[2];break;
				case 3:currentPosition=x[3];break;
				case 4:currentPosition=x[4];break;
				}			
				
				
			}
			
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				if(main.isInRiskZone(main.getDirectionPointArray(), currentPosition)){
					callManualYellow();
					Toast.makeText(ChangeStatus.this, "You are in Risk Zone.", 3).show();
					
				}else{
					timeCheckPosition.start();
					count++;
					Toast.makeText(ChangeStatus.this, "You are safe.", 3).show();
				}
				Toast.makeText(ChangeStatus.this, ""+new MemberUser().getFirstname()+"||"+new MemberUser().getEmail()+" || "+new MemberUser().getId(), 3).show();
				isRisk = false;
				status = "green";
				Log.d("isRisk",""+isRisk);
				Log.d("Status",""+status);
				Log.d("Lat/Lng",""+myLocation().latitude+","+myLocation().longitude);
				/*setMemberUserValue(myLocation());
				updateLog(memUser);*/
				
			}
		}.start();
		
	}
	
	public void setMemberUserValue(LatLng currentPosition){		
			
			memUser.setId(new MemberUser().getId());
			memUser.setEmail(new MemberUser().getEmail());
			memUser.setPassword(new MemberUser().getPassword());
			memUser.setFirstname(new MemberUser().getFirstname());
			memUser.setLastname(new MemberUser().getLastname());
			memUser.setPhoneNum(new MemberUser().getPhoneNum());
			memUser.setTimeLocateUpdate(new MemberUser().getTimeLocateUpdate());
			memUser.setPinCode(new MemberUser().getPinCode());
			memUser.setMsgRed(new MemberUser().getMsgRed());
			memUser.setMsgYellow(new MemberUser().getMsgYellow());
			memUser.setConfirmation(new MemberUser().getConfirmation());
			memUser.setType(new MemberUser().getType());
			memUser.setStatus(status);
			memUser.setIsRisk(""+isRisk);
			memUser.setLatitude(""+currentPosition.latitude);
			memUser.setLongitude(""+currentPosition.longitude);
			Log.d("isRisk",""+isRisk);
			Log.d("Status",""+status);
			Log.d("Logsssss",""+memUser.getId());
			Log.d("Logsssss",""+memUser.getEmail());
			Log.d("Logsssss",""+memUser.getLatitude());
			Log.d("Logsssss",""+memUser.getLongitude());
			Log.d("Logsssss",""+memUser.getId());
			Log.d("Logsssss",""+memUser.getId());
		
		
	}
	
	public void updateLog(MemberUser memUser){
		
		
		log.setDataForUpdateLog(memUser);
		/*log.setUser_id(memUser.getId());
		Log.d("PrintLog",""+log.getUser_id());*/
		userLog.setVariable(log);
		userLog.callRun();
	}

}
